﻿$(function(){
    var $result = $("#result");
    var $submit = $("#submit");
    $("#file").on("change", function(evt) {
        // remove content
        $result.html("");
        // be sure to show the results
        $("#result_block").removeClass("hidden").addClass("show");

        // Closure to capture the file information.
        function handleFile(f) {
            //添加页面提示正在解析zip文件,并且禁用提交按钮
            $result.html("正在解析文件，请稍后...")
            $submit.attr("disabled",true);
            var $title = $("<h4>", {
                text : f.name
            });
            var $fileContent = $("<ul>");
            var fileType = f.name.substring(f.name.lastIndexOf("."));
            if(fileType != ".zip"){
                $result.append($("<h4>", {text : "所选文件不是zip文件，请选择一个zip文件"}));
                return;
            }
            var bucket = f.name.substring(f.name.lastIndexOf("\\") + 1, f.name.indexOf(".zip"));

            var dateBefore = new Date();
            JSZip.loadAsync(f).then(function(zip) {
                    var dateAfter = new Date();
                    $result.html("");
                    $result.append($title);
                    $result.append($fileContent);
                    $title.append($("<span>", {
                        "class": "small",
                        text:" (loaded in " + (dateAfter - dateBefore) + "ms)"
                    }));
                    var map = Object.create(null);
                    zip.forEach(function (relativePath, zipEntry) {  // 2) print entries
                        var entryName = zipEntry.name;
                        //对于子文件夹做去"/"的处理
                        if (entryName.lastIndexOf("/") == entryName.length - 1){
                            entryName = entryName.substring(0, entryName.length - 1);
                        }
                        $fileContent.append($("<li>", {
                            text : entryName
                        }));
                        map[bucket + "/" + entryName] = entryName;
                    });

                    var jsonMap = _mapToJson(map);
                    //将解析好的jsonMap的值放入input中
                    $("#jsonMap").val(jsonMap);
                    //启用提交按钮
                    $submit.attr("disabled",false);

                    // //已获取到jsonMap 通过ajax传入后台
                    // $.ajax({
                    //     url: $("#path").val() + "/file/mapResolve.form",
                    //     dataType: 'json',
                    //     method: 'POST',
                    //     data: {"jsonMap": jsonMap},
                    //     success: function(data) {
                    //         console.log("返回信息为：" + data);
                    //     },
                    //     error: function(xhr) {
                    //         // 导致出错的原因较多，以后再研究
                    //         console.log('error:' + JSON.stringify(xhr));
                    //     }
                    // }).done(function(data) {
                    //         // 请求成功后要做的工作
                    //         console.log('success');
                    //     })
                    //     .fail(function() {
                    //         // 请求失败后要做的工作
                    //         console.log('error');
                    //     })
                    //     .always(function() {
                    //         // 不管成功或失败都要做的工作
                    //         console.log('complete');
                    //     });
                    // //调用ajax结束
                    // console.log(jsonMap);



                }, function (e) {
                    $result.append($("<div>", {
                        "class" : "alert alert-danger",
                        text : "Error reading " + f.name + ": " + e.message
                    }));
                });
        }

        var files = evt.target.files;
        for (var i = 0; i < files.length; i++) {
            handleFile(files[i]);
        }
    });
});

function submitForm() {
    var $result = $("#result");
    var formData = new FormData($( "#uploadForm" )[0]);
    var jsonMap = $("#jsonMap").val();
    var $submit = $("#submit");

    if(jsonMap == null || jsonMap == undefined || jsonMap == ""){
        return false;
    }
    $result.html("文件正在上传中，请稍后...");
    $submit.attr("disabled",true);
    var dateBefore = new Date();
    $.ajax({
        url: $("#path").val() + "/file/resolve.form",
        type: 'POST',
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        data: formData,
        dataType: 'json',
        async: true,
        cache: false,
        contentType: false,
        processData: false,
        success: function (data) {
            var dateAfter = new Date();
            $result.html("upload result : " + data.result + "</br>upload message : " + data.message + "</br>used time : " + (dateAfter - dateBefore)+
                "ms");
        },
        error: function (data) {
            var dateAfter = new Date();
            $result.html("upload result : " + data.result + "</br>upload message : " + data.message + "</br>used time : " + (dateAfter - dateBefore)+
                "ms");
            console.log('error:' + JSON.stringify(data));
        }
    }).always(function () {
        $submit.attr("disabled",false);
    });
}


function _strMapToObj(strMap){
    var obj = Object.create(null);
    for (var key in strMap) {
        obj[key] = strMap[key];
    }
    return obj;
}
/**
 *map转换为json
 */
function _mapToJson(map) {
    return JSON.stringify(this._strMapToObj(map));
}
